<template>
  <ele-page>
    <!-- 搜索表单 -->
    <user-search @search="reload" />
    <ele-card :body-style="{ paddingTop: '8px' }">
      <!-- 表格 -->
      <ele-pro-table
        ref="tableRef"
        row-key="userId"
        :columns="columns"
        :datasource="datasource"
        :show-overflow-tooltip="true"
        v-model:selections="selections"
        highlight-current-row
        cache-key="systemUserTable"
        :where="defaultWhere"
      >
        <template #toolbar>
          <el-button
            type="success"
            class="ele-btn-icon"
            :icon="Plus"
            @click="openEdit()"
          >
            新建
          </el-button>
        </template>

        <template #area="{ row }">
          <el-tag
            v-for="item in row.area_id"
            :key="item.id"
            size="small"
            :disable-transitions="true"
            style="margin-right: 6px"
          >
            {{ item.title }}
          </el-tag>
        </template>
        <template #status="{ row }">
          <el-switch
            size="small"
            :model-value="row.status === 1"
            @change="(checked) => editStatus(checked, row)"
          />
        </template>
        <template #action="{ row }">
          <el-link type="primary" :underline="false" @click="openEdit(row)">
            修改
          </el-link>
          <el-divider direction="vertical" />
          <el-link type="info" :underline="false" @click="resetPsw(row)">
            重置密码
          </el-link>
        </template>
      </ele-pro-table>
    </ele-card>
    <!-- 编辑弹窗 -->
    <user-edit v-model="showEdit" :data="current" @done="reload" />
  </ele-page>
</template>

<script setup>
  import { ref } from 'vue';
  import { Plus } from '@element-plus/icons-vue';
  import { ElMessageBox } from 'element-plus/es';
  import { EleMessage } from 'ele-admin-plus/es';
  import UserSearch from './components/user-search.vue';
  import UserEdit from './components/user-edit.vue';
  import {
    pageUsers,
    updateUserStatus,
    updateUserPassword
  } from '@/api/system/user';

  /** 表格实例 */
  const tableRef = ref(null);

  /** 表格列配置 */
  const columns = ref([
    {
      prop: 'id',
      width: 90,
      label: 'ID'
    },
    {
      prop: 'username',
      label: '用户账号',
      width: 120
    },
    {
      prop: 'realname',
      label: '姓名',
      width: 120,
      slot: 'realname'
    },
    {
      prop: 'rolesText',
      label: '部门',
      width: 120,
      slot: 'roles'
    },
    {
      label: '所属区域',
      minWidth: 120,
      slot: 'area'
    },
    {
      prop: 'status',
      label: '状态',
      width: 90,
      align: 'center',
      sortable: 'custom',
      slot: 'status'
    },
    {
      columnKey: 'action',
      label: '操作',
      width: 200,
      align: 'center',
      slot: 'action'
    }
  ]);

  /** 表格选中数据 */
  const selections = ref([]);

  /** 当前编辑数据 */
  const current = ref(null);

  /** 是否显示编辑弹窗 */
  const showEdit = ref(false);

  const defaultWhere = ref({
    status: 1
  });

  /** 表格数据源 */
  const datasource = ({ page, limit, where, orders }) => {
    return pageUsers({
      ...where,
      ...orders,
      page,
      limit
    });
  };

  /** 搜索 */
  const reload = (where) => {
    selections.value = [];
    tableRef.value?.reload?.({ page: 1, where });
  };

  /** 打开编辑弹窗 */
  const openEdit = (row) => {
    current.value = row ?? null;
    showEdit.value = true;
  };

  /** 重置用户密码 */
  const resetPsw = (row) => {
    ElMessageBox.prompt(`请输入用户"${row.realname}"的新密码：`, '重置密码', {
      inputPattern: /^[\S]{5,18}$/,
      inputErrorMessage: '密码必须为5-18位非空白字符',
      customStyle: { '--ele-message-box-body-padding': '4px 20px 0 20px' },
      draggable: true
    })
      .then(({ value }) => {
        const loading = EleMessage.loading('请求中..');
        updateUserPassword({ id: row.id, password: value })
          .then((msg) => {
            loading.close();
            EleMessage.success(msg);
          })
          .catch((e) => {
            loading.close();
            EleMessage.error(e.message);
          });
      })
      .catch(() => {});
  };

  /** 修改用户状态 */
  const editStatus = (checked, row) => {
    const status = checked ? 1 : 0;
    updateUserStatus({ id: row.id, status })
      .then((msg) => {
        row.status = status;
        reload();
        EleMessage.success(msg);
      })
      .catch((e) => {
        EleMessage.error(e.message);
      });
  };
</script>

<script>
  export default {
    name: 'SystemUser'
  };
</script>
